﻿module Sustainalytics.ProductInvolvement {

    import Common = Sustainalytics.Common;
    import Pager = Sustainalytics.Pager;

    // Assessments List controller
    export class CompanyAssessmentListController {

        // order by
        public orderByCol: string;
        public orderByAsc: boolean;

        // list of assessments
        public assessmentsList: PIAssessmentListDto[];

        // total number of assessments
        public assessmentCount: number;

        private scopeDestroyed: boolean;

        // permissions
        //public piPermissions: ProductInvolvement.Security.PIPermissions;

        public hasMultiCompanyPI: boolean;

        public notIncludedInUserUniverses: boolean;
        public noEvidenceFoundInIndicatorsOfInterest: boolean;
        public noClaims: boolean;

        private accountId: string;
        private userId: string;

        //filter options
        public piIndicatorSymbolsOptions: any[] = [];
        public myEvents: any;

        public piRangeOwnershipOptions: any[] = [
            { id: "N/A", label: "N/A" },
            { id: "0-4.9%", label: "0-4.9%" },
            { id: "5-9.9%", label: "5-9.9%" },
            { id: "10-24.9%", label: "10-24.9%" },
            { id: "25-49.9%", label: "25-49.9%" },
            { id: "50-100%", label: "50-100%" }
        ];

        public piRangeOwnershipFilterSettings: any = { scrollableHeight: '300px', scrollable: true };

        //filter values
        public piIndicatorSymbolsFilter: any[] = [];
        public piRangeOwnershipFilter: any[] = [];

        //filter value object
        public piFilterObject: PIAssessmentListFilters = new PIAssessmentListFilters();

        // Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $location: ng.ILocationService,
            private CompanyAssessmentService: ICompanyAssessmentService,
            private PIPermissionsService: ProductInvolvement.Security.IPIPermissionsService,
            private notificationFactory: Common.INotificationFactory,
            private staticObjects: Common.IStaticObjects) {

            var ctx = this;

            ctx.myEvents = {
                onMultiSelectBlur: function () {
                    ctx.searchButtonClick();
                }
            };

            $scope['assessmentsList'] = ctx;

            ctx.scopeDestroyed = false;


            // get permissions
            ctx.hasMultiCompanyPI = ctx.PIPermissionsService.hasMultiCompanyPI();

            if (!ctx.hasMultiCompanyPI) {
                // redirect to Overview tab
                //this.$location.path('/research/' + ctx.companyNameQueryString);
            }

            //load PI indicators
            ctx.loadPIIndicators();

            //ctx.loadOwnershipValues();

            ctx.orderByCol = "CompanyNameLowerCase";
            ctx.orderByAsc = true;

            //get accountId and userId to invalidate cache
            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }
            ctx.accountId = ctx.$rootScope['userInfo'].accountId;
            ctx.userId = ctx.$rootScope['userInfo'].userId;

            ctx.handlePagerChanged();
            ctx.handleScopeDestroyed();
        }
            
        // when scope is destroyed keep a flag to prevent some operations
        // eg: bootstrap UI tab delete each tab and select the next that causing 
        // in current case to trigger multiple requests while tabs are being disposed 
        // which is unnecessary
        private handleScopeDestroyed() {
            var ctx = this;

            // when scope is destroyed
            ctx.$scope.$on('$destroy', function () {
                ctx.scopeDestroyed = true;
            });            
        }

        // search for company assessments when pager changes
        private handlePagerChanged() {
            var ctx = this;

            ctx.$scope.$on('pagerChanged', function (ev, pager: Pager.PagerController) {
                ctx.getAssessments();
            });
        }


        // order list of portfolios
        public setOrderByCol(col: string) {
            var ctx = this;

            if (ctx.orderByCol === col) {
                ctx.orderByAsc = !ctx.orderByAsc;
            }
            else {
                ctx.orderByCol = col;
                ctx.orderByAsc = true;
            }
            ctx.getAssessments();
        }

        public searchButtonClick() {
            var ctx = this;

            // go to page 1
            var pager: Pager.PagerController = ctx.$scope['pager'];
            if (!pager)
                return;

            pager.goTo(1);
        }

        private loadOwnershipValues(): ng.IPromise<string[]> {
            var ctx = this;
            var getPromise: ng.IPromise<string[]> = ctx.CompanyAssessmentService.getOwnershipValues();
            getPromise.then((vals: string[]) => {

                vals.forEach(obj => {
                    ctx.piRangeOwnershipOptions.push({ id: obj, label: obj });
                });

            });
            return getPromise;
        }


        private loadPIIndicators(): ng.IPromise<PIIndicatorDto[]> {
            var ctx = this;
            var getPromise: ng.IPromise<PIIndicatorDto[]> = ctx.CompanyAssessmentService.getPIIndicators();
            getPromise.then((piIndicators: PIIndicatorDto[]) => {
                //ctx.piIndicators = piIndicators;
                piIndicators.forEach(obj => {
                    ctx.piIndicatorSymbolsOptions.push({ id: obj.symbol, label:obj.name});
                });
            });
            return getPromise;
        }

        // search list of assessments
        public getAssessments(): ng.IPromise<Common.PagedList<PIAssessmentListDto>> {
            var ctx = this;

            ctx.$rootScope['loading'] = true;
            
            var pager: Pager.PagerController = ctx.$scope['pager'];
            if (!pager) {
                var def = ctx.$q.defer();
                def.reject();
                return def.promise;
            }

            var skip = pager.skipCount();
            var take = pager.takeCount();


            //prepare filter object
            ctx.piFilterObject.companyNameLowerCase = angular.lowercase(ctx.piFilterObject.companyNameLowerCase);
            ctx.piFilterObject.industry = angular.lowercase(ctx.piFilterObject.industry);

            //ctx.piFilterObject.piIndicatorSymbolsFilter = [];
            ctx.piFilterObject.piIndicatorSymbolsStrFilter = "";
            if (ctx.piIndicatorSymbolsFilter && ctx.piIndicatorSymbolsFilter.length > 0)
            {
                var temp: string[] = []; 
                ctx.piIndicatorSymbolsFilter.forEach(obj => {
                    //ctx.piFilterObject.piIndicatorSymbolsFilter.push(obj.id);
                    temp.push(obj.id);
                    ctx.piFilterObject.piIndicatorSymbolsStrFilter = temp.join("|");
                });
            }

            //ctx.piFilterObject.piRangeOwnershipFilter = [];
            ctx.piFilterObject.piRangeOwnershipStrFilter = "";
            if (ctx.piRangeOwnershipFilter && ctx.piRangeOwnershipFilter.length > 0) {
                var temp: string[] = []; 
                ctx.piRangeOwnershipFilter.forEach(obj => {
                    //ctx.piFilterObject.piRangeOwnershipFilter.push(obj.id);
                    temp.push(obj.id);
                    ctx.piFilterObject.piRangeOwnershipStrFilter = temp.join("|");
                });
            }

            //get assessments count
            var pagedListPromise: ng.IPromise<Common.PagedList<PIAssessmentListDto>> =
                ctx.CompanyAssessmentService.getCompanyAssessmentsPagedList(ctx.piFilterObject, skip, take, [ctx.orderByCol], ctx.orderByAsc, ctx.accountId);

            pagedListPromise
                .then(function (pagedList: Common.PagedList<PIAssessmentListDto>)
                {
                    ctx.assessmentsList = pagedList.items;
                    ctx.assessmentCount = pagedList.totalItemsCount;
                    pager.setTotalItemsCount(pagedList.totalItemsCount);
                },
                (reason) =>
                {
                    if (reason.status == 404) {
                        if (reason.data.errCode == "PICompanyAssessmentShortReportEmptyNoUniversesException") {
                            ctx.notIncludedInUserUniverses = true;
                        }
                        if (reason.data.errCode == "PICompanyAssessmentShortReportEmptyNoClaimsException") {
                            ctx.noEvidenceFoundInIndicatorsOfInterest = true;
                        }
                    }
                    if (reason.status == 401) {
                        ctx.noClaims = true;
                    }
                })
                ['finally'](function () {
                    ctx.$rootScope['loading'] = false;
                });

            return pagedListPromise;
        }   
    }


    // register controller with ProductInvolvement module
    angular.module('Sustainalytics.ProductInvolvement').controller('CompanyAssessmentListController',
        ['$rootScope', '$scope', '$q', '$location', 'CompanyAssessmentService', 'PIPermissionsService', 'notificationFactory', 'staticObjects', CompanyAssessmentListController]);
} 